<template>
  <div class="chat-container">
    <div class="chat-wrapper">
      <!-- 会话列表 -->
      <div class="conversation-list">
        <div class="list-header">
          <h3>会话列表</h3>
        </div>
        <div class="list-content">
          <el-empty v-if="conversations.length === 0" description="暂无会话" />
          <div
            v-for="conv in conversations"
            :key="conv.userId"
            class="conversation-item"
            :class="{ active: currentConversation?.userId === conv.userId }"
            @click="selectConversation(conv)"
          >
            <el-avatar :size="45" :src="conv.avatar">{{ conv.nickname?.[0] }}</el-avatar>
            <div class="conv-info">
              <div class="conv-header">
                <span class="nickname">{{ conv.nickname }}</span>
                <span class="time">{{ formatTime(conv.lastTime) }}</span>
              </div>
              <div class="last-message">{{ conv.lastMessage }}</div>
            </div>
            <el-badge v-if="conv.unreadCount > 0" :value="conv.unreadCount" class="unread-badge" />
          </div>
        </div>
      </div>

      <!-- 聊天窗口 -->
      <div class="chat-window">
        <div v-if="!currentConversation" class="no-conversation">
          <el-icon :size="80"><ChatDotRound /></el-icon>
          <p>选择一个会话开始聊天</p>
        </div>

        <template v-else>
          <!-- 聊天头部 -->
          <div class="chat-header">
            <el-avatar :size="40" :src="currentConversation.avatar">
              {{ currentConversation.nickname?.[0] }}
            </el-avatar>
            <span class="chat-user">{{ currentConversation.nickname }}</span>
          </div>

          <!-- 消息列表 -->
          <div class="message-list" ref="messageListRef">
            <div
              v-for="msg in messages"
              :key="msg.id"
              class="message-item"
              :class="{ 'is-mine': msg.senderId === userId }"
              @mouseenter="msg.showActions = true"
              @mouseleave="msg.showActions = false"
            >
              <el-avatar :size="35" :src="msg.senderId === userId ? userInfo?.avatar : currentConversation.avatar">
                {{ msg.senderId === userId ? userInfo?.nickname?.[0] : currentConversation.nickname?.[0] }}
              </el-avatar>
              <div class="message-content">
                <!-- 撤回的消息 -->
                <div v-if="msg.recalled === 1" class="message-text recalled">
                  <el-icon><Close /></el-icon>
                  消息已撤回
                </div>
                <!-- 文字消息 -->
                <div v-else-if="msg.messageType === 1" class="message-text">{{ msg.content }}</div>
                <!-- 图片消息 -->
                <div v-else-if="msg.messageType === 2" class="message-image">
                  <el-image 
                    :src="msg.content" 
                    :preview-src-list="[msg.content]"
                    fit="cover"
                    style="max-width: 200px; max-height: 200px; border-radius: 8px;"
                  />
                </div>
                <!-- 表情消息 -->
                <div v-else-if="msg.messageType === 3" class="message-emoji">
                  {{ msg.content }}
                </div>
                <div class="message-footer">
                  <span class="message-time">{{ formatTime(msg.createTime) }}</span>
                  <!-- 撤回按钮 -->
                  <el-button
                    v-if="msg.senderId === userId && msg.recalled !== 1 && msg.showActions && canRecall(msg.createTime)"
                    text
                    size="small"
                    type="danger"
                    @click="handleRecallMessage(msg)"
                  >
                    撤回
                  </el-button>
                </div>
              </div>
            </div>
          </div>

          <!-- 输入框 -->
          <div class="message-input">
            <div class="input-toolbar">
              <!-- 表情按钮 -->
              <el-popover placement="top" :width="300" trigger="click">
                <template #reference>
                  <el-button text>
                    <el-icon><ChatLineSquare /></el-icon>
                    表情
                  </el-button>
                </template>
                <div class="emoji-picker">
                  <span
                    v-for="emoji in emojis"
                    :key="emoji"
                    class="emoji-item"
                    @click="insertEmoji(emoji)"
                  >
                    {{ emoji }}
                  </span>
                </div>
              </el-popover>
              
              <!-- 图片按钮 -->
              <el-button text @click="triggerImageUpload">
                <el-icon><Picture /></el-icon>
                图片
              </el-button>
              <input
                ref="imageInputRef"
                type="file"
                accept="image/*"
                style="display: none"
                @change="handleImageUpload"
              />
            </div>
            <el-input
              v-model="inputMessage"
              type="textarea"
              :rows="3"
              placeholder="输入消息..."
              @keyup.ctrl.enter="sendMessage"
            />
            <el-button type="primary" @click="sendMessage" :disabled="!inputMessage.trim()">
              发送 (Ctrl+Enter)
            </el-button>
          </div>
        </template>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Close, ChatLineSquare, Picture, ChatDotRound } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'
import websocketService from '@/utils/websocket'
import { getChatHistory, markAsRead, recallMessage } from '@/api/chat'
import { uploadImage } from '@/api/file'
import { getUserById } from '@/api/auth'
import dayjs from 'dayjs'
import relativeTime from 'dayjs/plugin/relativeTime'
import 'dayjs/locale/zh-cn'

dayjs.extend(relativeTime)
dayjs.locale('zh-cn')

const router = useRouter()
const userStore = useUserStore()
const userInfo = ref(userStore.userInfo)
const userId = ref(userInfo.value?.id)

// 使用Map存储会话，键为用户ID
const conversationsMap = new Map()
const conversations = ref([])

const currentConversation = ref(null)
const messages = ref([])
const inputMessage = ref('')
const messageListRef = ref(null)
const imageInputRef = ref(null)

// 表情列表
const emojis = [
  '😀', '😁', '😂', '🤣', '😃', '😄', '😅', '😆',
  '😊', '😋', '😎', '😍', '😘', '😗', '😙', '😚',
  '🙂', '🤗', '🤩', '🤔', '🤨', '😐', '😑', '😶',
  '🙄', '😏', '😣', '😥', '😮', '🤐', '😯', '😪',
  '😫', '😴', '😌', '😛', '😜', '😝', '🤤', '😒',
  '😓', '😔', '😕', '🙃', '🤑', '😲', '☹️', '🙁',
  '😖', '😞', '😟', '😤', '😢', '😭', '😦', '😧',
  '😨', '😩', '🤯', '😬', '😰', '😱', '🥵', '🥶',
  '😳', '🤪', '😵', '😡', '😠', '🤬', '😷', '🤒',
  '🤕', '🤢', '🤮', '🤧', '😇', '🥳', '🥺', '🤠',
  '👍', '👎', '👏', '🙌', '👋', '🤝', '💪', '🙏',
  '❤️', '💔', '💕', '💖', '💗', '💙', '💚', '💛',
  '🎉', '🎊', '🎈', '🎁', '🏆', '🌟', '⭐', '✨'
]

const formatTime = (time) => {
  if (!time) return ''
  return dayjs(time).fromNow()
}

const selectConversation = async (conv) => {
  currentConversation.value = conv
  
  // 标记为已读
  if (conv.unreadCount > 0) {
    conv.unreadCount = 0
    try {
      await markAsRead(userId.value, conv.userId)
    } catch (error) {
      console.error('标记已读失败：', error)
    }
  }
  
  // 加载聊天历史
  await loadMessages(conv.userId)
}

const loadMessages = async (otherUserId) => {
  try {
    const res = await getChatHistory({
      userId1: userId.value,
      userId2: otherUserId,
      limit: 50
    })
    
    // 按时间排序（从旧到新）
    messages.value = (res.data || []).sort((a, b) => 
      new Date(a.createTime) - new Date(b.createTime)
    )
    
    scrollToBottom()
  } catch (error) {
    console.error('加载聊天历史失败：', error)
    messages.value = []
  }
}

// 修改原有的 sendMessage 方法，添加消息类型支持
const sendMessage = () => {
  const content = inputMessage.value.trim()
  if (!content || !currentConversation.value) return
  
  // 检查是否为纯表情消息（长度小于5且都是表情）
  const isEmoji = content.length <= 5 && /^[\u{1F300}-\u{1F9FF}]+$/u.test(content)
  
  const message = {
    senderId: userId.value,
    receiverId: currentConversation.value.userId,
    messageType: isEmoji ? 3 : 1, // 3-表情 1-文字
    content: content
  }
  
  websocketService.sendMessage(message)
  
  // 清空输入框
  inputMessage.value = ''
  
  // 更新会话最后消息
  updateConversationLastMessage(
    currentConversation.value.userId,
    isEmoji ? content : content
  )
}
const scrollToBottom = () => {
  nextTick(() => {
    if (messageListRef.value) {
      messageListRef.value.scrollTop = messageListRef.value.scrollHeight
    }
  })
}

const onMessageReceived = async (message) => {
  const otherUserId = message.senderId === userId.value ? message.receiverId : message.senderId;
  
  // 如果是当前会话的消息，添加到列表
  if (currentConversation.value && otherUserId === currentConversation.value.userId) {
    messages.value.push(message)
    scrollToBottom()
    
    // 标记为已读
    if (message.senderId !== userId.value) {
      try {
        await markAsRead(userId.value, message.senderId)
      } catch (error) {
        console.error('标记已读失败：', error)
      }
    }
  }
  
  // 更新或创建会话
  let conv = conversationsMap.get(otherUserId)
  if (!conv) {
    // 获取用户信息并创建新会话
    try {
      const userRes = await getUserById(otherUserId)
      conv = {
        userId: otherUserId,
        nickname: userRes.data.nickname,
        avatar: userRes.data.avatar,
        lastMessage: message.content,
        lastTime: new Date(message.createTime),
        unreadCount: 0
      }
      conversationsMap.set(otherUserId, conv)
      conversations.value.unshift(conv)
    } catch (error) {
      console.error('获取用户信息失败：', error)
      return
    }
  } else {
    conv.lastMessage = message.content
    conv.lastTime = new Date(message.createTime)
    
    // 如果不是当前会话，增加未读数
    if (!currentConversation.value || otherUserId !== currentConversation.value.userId) {
      if (message.senderId !== userId.value) {
        conv.unreadCount++
      }
    }
    
    // 将会话移到列表顶部
    const index = conversations.value.findIndex(c => c.userId === otherUserId)
    if (index > 0) {
      conversations.value.splice(index, 1)
      conversations.value.unshift(conv)
    }
  }
}

onMounted(async () => {
  if (!userInfo.value) {
    await userStore.fetchUserInfo()
    userInfo.value = userStore.userInfo
    userId.value = userInfo.value.id
  }
  
  // 连接WebSocket
  const token = userStore.token
  if (token) {
    try {
      websocketService.connect(token, onMessageReceived)
      ElMessage.success('聊天服务已连接')
    } catch (error) {
      console.error('WebSocket连接失败：', error)
      ElMessage.warning('聊天服务连接失败，消息可能无法实时接收')
    }
  }
  
  // 如果从URL参数传入了用户ID，则创建会话
  const targetUserId = router.currentRoute.value.query.userId
  if (targetUserId) {
    await createConversation(parseInt(targetUserId))
  }
})

// 创建新会话
const createConversation = async (targetUserId) => {
  if (conversationsMap.has(targetUserId)) {
    // 如果会话已存在，直接选择
    const conv = conversationsMap.get(targetUserId)
    await selectConversation(conv)
    return
  }
  
  try {
    // 获取目标用户信息
    const userRes = await getUserById(targetUserId)
    const conv = {
      userId: targetUserId,
      nickname: userRes.data.nickname,
      avatar: userRes.data.avatar,
      lastMessage: '开始对话...',
      lastTime: new Date(),
      unreadCount: 0
    }
    
    conversationsMap.set(targetUserId, conv)
    conversations.value.unshift(conv)
    await selectConversation(conv)
  } catch (error) {
    console.error('创建会话失败：', error)
    ElMessage.error('无法创建会话')
  }
}

onUnmounted(() => {
  websocketService.disconnect()
})
const canRecall = (createTime) => {
  if (!createTime) return false
  const now = dayjs()
  const msgTime = dayjs(createTime)
  const diff = now.diff(msgTime, 'minute')
  return diff < 2
}

// 处理撤回消息
const handleRecallMessage = async (msg) => {
  try {
    await ElMessageBox.confirm('确定要撤回这条消息吗？', '提示', {
      type: 'warning'
    })
    
    await recallMessage(msg.id, userId.value)
    
    // 更新本地消息状态
    msg.recalled = 1
    msg.content = '消息已撤回'
    
    ElMessage.success('撤回成功')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('撤回失败：', error)
      ElMessage.error('撤回失败')
    }
  }
}

// 插入表情
const insertEmoji = (emoji) => {
  inputMessage.value += emoji
}

// 触发图片上传
const triggerImageUpload = () => {
  imageInputRef.value?.click()
}

// 处理图片上传
const handleImageUpload = async (event) => {
  const file = event.target.files?.[0]
  if (!file) return
  
  // 验证文件类型
  if (!file.type.startsWith('image/')) {
    ElMessage.error('只能上传图片文件')
    return
  }
  
  // 验证文件大小（5MB）
  if (file.size > 5 * 1024 * 1024) {
    ElMessage.error('图片大小不能超过5MB')
    return
  }
  
  try {
    // 显示上传提示
    ElMessage.info('正在上传图片...')
    
    // 上传图片（直接传file对象，uploadImage会处理FormData）
    const res = await uploadImage(file)
    
    // 发送图片消息
    if (res.data) {
      sendImageMessage(res.data)
      ElMessage.success('图片发送成功')
    }
    
    // 清空input
    event.target.value = ''
  } catch (error) {
    console.error('上传图片失败：', error)
    ElMessage.error('上传图片失败')
  }
}

// 发送图片消息
const sendImageMessage = (imageUrl) => {
  if (!currentConversation.value) return
  
  const message = {
    senderId: userId.value,
    receiverId: currentConversation.value.userId,
    messageType: 2, // 图片消息
    content: imageUrl
  }
  
  websocketService.sendMessage(message)
  
  // 更新会话最后消息
  updateConversationLastMessage(currentConversation.value.userId, '[图片]')
}
</script>

<style scoped>
.chat-container {
  min-height: 100%;
  padding: 24px;
  animation: fadeIn 0.5s ease-out;
}

.chat-wrapper {
  max-width: 1300px;
  margin: 0 auto;
  display: flex;
  height: 700px;
  background: white;
  border-radius: 20px;
  overflow: hidden;
  box-shadow: 0 8px 32px rgba(102, 126, 234, 0.12);
  border: 1px solid rgba(102, 126, 234, 0.1);
}

/* 会话列表 */
.conversation-list {
  width: 320px;
  border-right: 1px solid #f0f2f5;
  display: flex;
  flex-direction: column;
  background: #fafbfc;
}

.list-header {
  padding: 24px 20px;
  border-bottom: 1px solid #f0f2f5;
  background: white;
}

.list-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 700;
  color: #333;
}

.list-content {
  flex: 1;
  overflow-y: auto;
}

.conversation-item {
  display: flex;
  align-items: center;
  padding: 16px 20px;
  cursor: pointer;
  transition: all 0.3s;
  position: relative;
  border-left: 3px solid transparent;
  margin: 4px 0;
}

.conversation-item:hover {
  background: rgba(102, 126, 234, 0.05);
  border-left-color: transparent;
}

.conversation-item.active {
  background: linear-gradient(90deg, rgba(102, 126, 234, 0.1) 0%, rgba(255, 255, 255, 0.5) 100%);
  border-left-color: #667eea;
}

.conversation-item .el-avatar {
  border: 2px solid #f0f2f5;
  transition: all 0.3s;
}

.conversation-item.active .el-avatar,
.conversation-item:hover .el-avatar {
  border-color: #667eea;
}

.conv-info {
  flex: 1;
  margin-left: 14px;
  overflow: hidden;
}

.conv-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 6px;
}

.nickname {
  font-weight: 600;
  font-size: 15px;
  color: #333;
}

.conversation-item.active .nickname {
  color: #667eea;
}

.time {
  font-size: 12px;
  color: #999;
  font-weight: 400;
}

.last-message {
  font-size: 13px;
  color: #666;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  line-height: 1.4;
}

.unread-badge {
  position: absolute;
  right: 20px;
  top: 50%;
  transform: translateY(-50%);
}

.unread-badge :deep(.el-badge__content) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
}

/* 聊天窗口 */
.chat-window {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: white;
}

.no-conversation {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #999;
  animation: fadeIn 0.6s ease-out;
}

.no-conversation .el-icon {
  color: #d0d4db;
  margin-bottom: 16px;
}

.no-conversation p {
  margin: 0;
  font-size: 16px;
  color: #999;
}

.chat-header {
  display: flex;
  align-items: center;
  padding: 20px 24px;
  border-bottom: 1px solid #f0f2f5;
  background: linear-gradient(135deg, rgba(102, 126, 234, 0.03) 0%, rgba(255, 255, 255, 1) 100%);
}

.chat-header .el-avatar {
  border: 2px solid #667eea;
}

.chat-user {
  margin-left: 14px;
  font-weight: 600;
  font-size: 17px;
  color: #333;
}

/* 消息列表 */
.message-list {
  flex: 1;
  padding: 24px;
  overflow-y: auto;
  background: linear-gradient(to bottom, #fafbfd 0%, #f7f8fa 100%);
}

.message-item {
  display: flex;
  margin-bottom: 24px;
  animation: slideInLeft 0.3s ease-out;
}

.message-item.is-mine {
  flex-direction: row-reverse;
  animation: slideInRight 0.3s ease-out;
}

.message-item .el-avatar {
  border: 2px solid #f0f2f5;
}

.message-content {
  max-width: 60%;
  margin: 0 14px;
}

.message-item.is-mine .message-content {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
}

.message-text {
  padding: 12px 16px;
  border-radius: 12px;
  background: white;
  word-break: break-word;
  line-height: 1.6;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  transition: all 0.3s;
}

.message-text:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.message-item.is-mine .message-text {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}

.message-item.is-mine .message-text:hover {
  box-shadow: 0 6px 16px rgba(102, 126, 234, 0.4);
}

.message-time {
  margin-top: 6px;
  font-size: 12px;
  color: #999;
  font-weight: 400;
}

/* 输入框 */
.message-input {
  padding: 20px 24px;
  border-top: 1px solid #f0f2f5;
  display: flex;
  gap: 12px;
  align-items: flex-end;
  background: white;
}

.message-input .el-textarea {
  flex: 1;
}

.message-input :deep(.el-textarea__inner) {
  border-radius: 12px;
  border-color: #e8ebf0;
  padding: 12px 16px;
  transition: all 0.3s;
}

.message-input :deep(.el-textarea__inner:focus) {
  border-color: #667eea;
  box-shadow: 0 0 0 2px rgba(102, 126, 234, 0.1);
}

.input-toolbar {
  display: flex;
  gap: 8px;
  padding: 12px 20px;
  border-bottom: 1px solid #f0f2f5;
  background: #fafbfc;
}

.input-toolbar .el-button {
  border-radius: 8px;
  transition: all 0.3s;
}

.input-toolbar .el-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.2);
}

/* 表情选择器 */
.emoji-picker {
  display: grid;
  grid-template-columns: repeat(8, 1fr);
  gap: 8px;
  max-height: 240px;
  overflow-y: auto;
  padding: 8px;
}

.emoji-item {
  font-size: 28px;
  cursor: pointer;
  text-align: center;
  padding: 8px;
  border-radius: 8px;
  transition: all 0.2s;
}

.emoji-item:hover {
  background: linear-gradient(135deg, rgba(102, 126, 234, 0.1) 0%, rgba(118, 75, 162, 0.1) 100%);
  transform: scale(1.3);
}

/* 消息样式 */
.message-image {
  cursor: pointer;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transition: all 0.3s;
}

.message-image:hover {
  transform: scale(1.02);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.15);
}

.message-image :deep(.el-image) {
  display: block;
}

.message-emoji {
  font-size: 56px;
  line-height: 1;
  padding: 8px;
  animation: pulse 0.6s ease-out;
}

.message-text.recalled {
  color: #999;
  font-style: italic;
  display: flex;
  align-items: center;
  gap: 6px;
  background: #f5f7fa;
  box-shadow: none;
}

.message-item.is-mine .message-text.recalled {
  background: #f5f7fa;
  color: #999;
}

.message-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 6px;
  gap: 8px;
}

.message-time {
  font-size: 12px;
  color: #999;
}

.message-footer .el-button {
  opacity: 0.6;
  transition: all 0.3s;
}

.message-footer .el-button:hover {
  opacity: 1;
  transform: scale(1.05);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .chat-container {
    padding: 12px;
  }

  .chat-wrapper {
    height: calc(100vh - 100px);
    border-radius: 12px;
  }

  .conversation-list {
    width: 280px;
  }

  .message-content {
    max-width: 75%;
  }

  .message-input {
    padding: 16px;
  }
}
</style>

